package com.example.teemor.es_demo.config;

import com.example.teemor.es_demo.service.LogConsumerService;
import com.example.teemor.es_demo.service.LogProducerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import jakarta.annotation.PreDestroy;
import java.util.concurrent.Executor;

/**
 * 日志管理系统配置类
 * 负责初始化日志管理相关的服务和配置
 */
@Slf4j
@Configuration
@EnableAsync
@EnableScheduling
@RequiredArgsConstructor
public class LogManagementConfig {
    
    private final LogProducerService logProducerService;
    private final LogConsumerService logConsumerService;
    
    /**
     * 异步任务执行器配置
     */
    @Bean(name = "logTaskExecutor")
    public Executor logTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("log-async-");
        executor.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    
    /**
     * 日志管理系统初始化
     */
    @Bean
    public CommandLineRunner logManagementInitializer() {
        return args -> {
            try {
                log.info("开始初始化日志管理系统...");
                
                // 初始化日志生产者服务
                logProducerService.init();
                log.info("日志生产者服务初始化完成");
                
                // 初始化日志消费者服务
                logConsumerService.init();
                log.info("日志消费者服务初始化完成");
                
                log.info("日志管理系统初始化完成");
                
            } catch (Exception e) {
                log.error("日志管理系统初始化失败", e);
                throw new RuntimeException("日志管理系统初始化失败", e);
            }
        };
    }
    
    /**
     * 应用关闭时的清理工作
     */
    @PreDestroy
    public void destroy() {
        try {
            log.info("开始销毁日志管理系统...");
            
            // 销毁日志生产者服务
            logProducerService.destroy();
            log.info("日志生产者服务已销毁");
            
            // 销毁日志消费者服务
            logConsumerService.destroy();
            log.info("日志消费者服务已销毁");
            
            log.info("日志管理系统销毁完成");
            
        } catch (Exception e) {
            log.error("日志管理系统销毁失败", e);
        }
    }
}